package com.spc.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.spc.dao.PermissionDao;
import com.spc.entity.PageResult;
import com.spc.entity.QueryPageBean;
import com.spc.pojo.Permission;
import com.spc.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;


    //分页查询所有的权限进行页面展示
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        //获取当前的页码，和每页显示条数,和查询的条件
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //用分页插件进行分页查询
        PageHelper.startPage(currentPage, pageSize);
        //进行条件查询
        Page<Permission> page = permissionDao.findByCondition(queryString);
        //获取总的数据条数和分页数据
        long total = page.getTotal();
        List<Permission> rows = page.getResult();


        return new PageResult(total,rows);
    }

    //新增权限
    @Override
    public void add(Permission permission) {
        permissionDao.add(permission);
    }

    //根据id查询权限
    @Override
    public Permission findById(Integer id) {

        Permission permission = permissionDao.findById(id);

        return permission;
    }

    //编辑权限
    @Override
    public void edit(Permission permission) {

        permissionDao.edit(permission);

    }

    //根据id删除权限
    @Override
    public void deleteById(Integer id) {

        //首先判断要删除的权限是否跟角色有关联，如果有，则不能删除
     Long count = permissionDao.conutRoleAndPermission(id);

        if(count > 0){
            //跟角色有关联，不能删除。创造个异常抛出
            throw new RuntimeException();

        }else{
            ////跟角色无关联，正常的进行删除
            permissionDao.deleteById(id);

        }
    }

    //查询所有权限信息
    @Override
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }
}
